package com.mvc.web.common.tag;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import com.mvc.web.common.utils.AESUtil;
import com.mvc.web.common.utils.MailUtil;
import com.mvc.web.common.utils.ToolsUtils;

/**
 * @Description: 按钮菜单权限标签类
 * @author 白海安 （baihaian@126.com） 2016年6月27日 下午2:39:45
 * @version V1.0
 */
public class PermissionTag extends SimpleTagSupport {
	// 自定义标签属性，用于标签传入参数
	private String code;

	// 接收标签传入的参数
	public void setCode(String code) {
		this.code = code;
	}
	public void doTag(){
		try {
			// 获取用户登陆后保存的Session
			HttpServletRequest request = (HttpServletRequest) ((PageContext) this.getJspContext()).getRequest();
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				String codes = "";
				String uid = "";
				for (Cookie c : cookies) {
					if ("logininfo".equals(c.getName())) {
						codes = AESUtil.base64AESDecrypt(c.getValue());
					} else if ("inner_logininfo".equals(c.getName())) {
						uid = AESUtil.base64AESDecrypt(c.getValue());
					}
				}
				if (uid.equals("1")) {// 超级管理员
					this.getJspBody().invoke(null);
				} else if (ToolsUtils.isNotEmpty(codes) && codes.contains(code)) {
					this.getJspBody().invoke(null); // 有权限输出标签体内容
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			if(e!=null){
				StringWriter sw = new StringWriter();   
		        e.printStackTrace(new PrintWriter(sw, true));   
		        String str = new SimpleDateFormat("yyyy-MM-ss HH:mm:ss sss").format(new Date())+"/n";
		        MailUtil mu = new MailUtil("快收单异常权限标签错误", str+sw.toString(), "baiha@jizhicar.com", null);
		        mu.sendEmail();
	        }
		}
	}
}
